<template>
  <div>
    <!--搜索区域-->
    <div style="margin: 10px 5px">
      <el-input v-model="searchForm.supplierCode" style="width: 20%" placeholder="供应商编码" @input="debounceSearch"/>
      <el-input v-model="searchForm.supplierName" style="width: 20%" placeholder="供应商名称" @input="debounceSearch"/>
      <el-select v-model="searchForm.level" placeholder="供应商等级" clearable style="width: 15%; margin-left: 10px" @change="search">
        <el-option value="S" label="S级(战略)" />
        <el-option value="A" label="A级(优质)" />
        <el-option value="B" label="B级(良好)" />
        <el-option value="C" label="C级(一般)" />
        <el-option value="D" label="D级(待观察)" />
      </el-select>
      <el-select v-model="searchForm.status" placeholder="供应商状态" clearable style="width: 15%; margin-left: 10px" @change="search">
        <el-option :value="1" label="启用" />
        <el-option :value="0" label="停用" />
      </el-select>
      <el-button style="margin: 0 10px" type="primary" @click="search">查询</el-button>
      <el-button type="primary" @click="reset">重置</el-button>
    </div>
    <!--功能按钮区域-->
    <div style="margin: 10px 5px">
      <el-button type="primary" @click="add">新增供应商</el-button>
      <el-button type="success" @click="importSuppliers">导入</el-button>
      <el-button type="warning" @click="exportSuppliers">导出</el-button>
    </div>
    <!--数据表格-->
    <el-table :data="tableData" ref="supplierTable" stripe style="width: 100%"
              @row-click="handleRowClick">
      <el-table-column type="selection" align="center"/>
      <el-table-column prop="supplierCode" label="供应商编码"  align="center"/>
      <el-table-column prop="supplierName" label="供应商名称"  align="center"/>
      <el-table-column prop="contactPerson" label="联系人"  align="center"/>
      <el-table-column prop="contactPhone" label="联系电话"  align="center"/>
      <el-table-column prop="address" label="地址" :show-overflow-tooltip="true" width="250" align="center"/>
      <el-table-column prop="email" label="邮箱"  :show-overflow-tooltip="true" align="center"/>

      <!-- 新增评分列 -->
      <el-table-column fixed="right" label="综合评分" width="200">
        <template #default="scope">
          <el-rate
            v-model="scope.row.displayScore"
            disabled
            :max="5"
            :allow-half="true"
            :colors="rateColors"
          />
          <span style="margin-left: 5px; color: #ff9900">{{ scope.row.totalScore }}分</span>
        </template>
      </el-table-column>

      <el-table-column prop="level" label="等级"  align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.level === 'S'" type="success">S级(战略)</el-tag>
          <el-tag v-else-if="scope.row.level === 'A'" type="primary">A级(优质)</el-tag>
          <el-tag v-else-if="scope.row.level === 'B'" type="info">B级(良好)</el-tag>
          <el-tag v-else-if="scope.row.level === 'C'" type="warning">C级(一般)</el-tag>
          <el-tag v-else-if="scope.row.level === 'D'" type="danger">D级(待观察)</el-tag>
          <el-tag v-else>{{scope.row.level}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态"  align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="170">
        <template #default="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作"  align="center" width="250">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
          <el-button link type="success" @click="handleEvaluate(scope.row)">评价</el-button>
          <el-popconfirm title="确定删除该供应商吗？" @confirm="handleDelete(scope.row.supplierId)">
            <template #reference>
              <el-button link type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div style="margin: 10px 0">
      <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!--供应商表单对话框-->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增供应商' : dialogType === 'edit' ? '编辑供应商' : '查看供应商'" width="60%">
      <el-form :model="form" :rules="rules" ref="supplierForm" label-width="120px" :disabled="dialogType === 'view'">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="supplierCode">
              <template #label>
                <span>
                  <el-tooltip content="供应商的唯一标识符，用于在系统中快速查找和追踪供应商" placement="top">
                    供应商编码
                  </el-tooltip>
                </span>
              </template>
              <el-input v-model="form.supplierCode" placeholder="请输入供应商编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="supplierName">
              <template #label>
                <span>
                  <el-tooltip content="供应商的名称，直观描述供应商，便于理解和识别" placement="top">
                    供应商名称
                  </el-tooltip>
                </span>
              </template>
              <el-input v-model="form.supplierName" placeholder="请输入供应商名称"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="contactPerson">
              <template #label>
                <span>
                  <el-tooltip content="供应商的联系人姓名，便于直接沟通" placement="top">
                    联系人
                  </el-tooltip>
                </span>
              </template>
              <el-input v-model="form.contactPerson" placeholder="请输入联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="contactPhone">
              <template #label>
                <span>
                  <el-tooltip content="联系人的电话号码，用于沟通联系" placement="top">
                    联系电话
                  </el-tooltip>
                </span>
              </template>
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="email">
              <template #label>
                <span>
                  <el-tooltip content="供应商的电子邮箱，用于电子通讯和发送合同等文档" placement="top">
                    邮箱
                  </el-tooltip>
                </span>
              </template>
              <el-input v-model="form.email" placeholder="请输入邮箱"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status">
              <template #label>
                <span>
                  <el-tooltip content="供应商状态，启用表示可以与该供应商开展业务，停用表示暂停与该供应商的合作" placement="top">
                    状态
                  </el-tooltip>
                </span>
              </template>
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item prop="address">
          <template #label>
            <span>
              <el-tooltip content="供应商的详细地址，用于物流配送和实地考察" placement="top">
                地址
              </el-tooltip>
            </span>
          </template>
          <el-input v-model="form.address" placeholder="请输入详细地址"/>
        </el-form-item>

        <el-form-item prop="remark">
          <template #label>
            <span>
              <el-tooltip content="关于供应商的额外信息，可记录合作历史、特殊要求等" placement="top">
                备注
              </el-tooltip>
            </span>
          </template>
          <el-input v-model="form.remark" type="textarea" rows="3" placeholder="请输入备注信息"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveSupplier" v-if="dialogType !== 'view'">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 评价对话框 -->
    <el-dialog v-model="evaluateDialogVisible" title="供应商评价" width="50%">
      <evaluation-form
        ref="evaluationForm"
        :supplier-id="currentSupplierId"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="evaluateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEvaluation">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!--导入对话框-->
    <el-dialog v-model="importDialogVisible" title="导入供应商" width="30%">
      <el-upload
        class="upload-demo"
        drag
        action="/api/supplier/import"
        :on-success="handleImportSuccess"
        :on-error="handleImportError"
        accept=".xls,.xlsx"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传Excel文件，且文件大小不超过500kb
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { UploadFilled } from '@element-plus/icons-vue'
import {
  listSuppliers,
  getSupplier,
  addSupplier,
  updateSupplier,
  deleteSupplier
} from "@/api/supplier"
import { addEvaluation } from "@/api/supplierEvaluation"
import EvaluationForm from '@/components/EvaluationForm.vue'

export default {
  name: 'SupplierView',
  components: {
    UploadFilled,
    EvaluationForm
  },
  data() {
    return {
      // 表格数据
      tableData: [],
      total: 0,
      // 搜索条件
      searchForm: {
        pageNum: 1,
        pageSize: 10
      },
      // 对话框控制
      dialogVisible: false,
      dialogType: 'add', // add, edit, view
      importDialogVisible: false,
      evaluateDialogVisible: false,
      currentSupplierId: null,
      // 表单数据
      form: {
        level: 'C',
        status: 1,
      },
      // 服务器验证错误信息
      serverValidErrors: {},
      // 表单验证规则
      rules: {
        supplierCode: [
          { required: true, message: "请输入供应商编码", trigger: "blur" },
          { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
        ],
        supplierName: [
          { required: true, message: "请输入供应商名称", trigger: "blur" },
          { min: 2, max: 100, message: "长度在 2 到 100 个字符", trigger: "blur" }
        ],
        contactPerson: [
          { required: true, message: "请输入联系人", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        email: [
          { pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/, message: "请输入正确的邮箱地址", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择供应商状态", trigger: "change" }
        ]
      },
      // 评分颜色配置：低分红色、中分黄色、高分绿色
      rateColors: ['#F56C6C', '#E6A23C', '#67C23A'],
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // 防抖搜索函数
    debounceSearch() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }

      this.searchTimer = setTimeout(() => {
        this.search();
      }, 250);
    },

    // 获取供应商列表
    getList() {
      listSuppliers(this.searchForm).then(res => {
        if (res.code === 200) {
          this.tableData = (res.rows || res.data.records).map(item => {
            return {
              ...item,
              displayScore: item.totalScore ? item.totalScore / 2 : 0,
            };
          });
          this.total = res.data.total;
        } else {
          this.$message.error('获取供应商列表失败');
        }
      });
    },

    // 搜索
    search() {
      this.searchForm.pageNum = 1;
      this.getList();
    },

    // 重置
    reset() {
      this.searchForm = {
        pageNum: 1,
        pageSize: 10
      };
      this.getList();
    },

    // 新增供应商
    add() {
      this.dialogType = 'add';
      this.dialogVisible = true;
      this.form = {
        level: 'D',
        status: 1,
      };
      // 清空表单验证
      if (this.$refs.supplierForm) {
        this.$refs.supplierForm.resetFields();
      }
      // 清空服务器验证错误
      this.serverValidErrors = {};
    },

    // 编辑供应商
    handleEdit(row) {
      this.dialogType = 'edit';
      this.dialogVisible = true;
      // 清空服务器验证错误
      this.serverValidErrors = {};
      getSupplier(row.supplierId).then(res => {
        if (res.code === 200) {
          this.form = res.data;
        } else {
          this.$message.error('获取供应商信息失败');
        }
      });
    },

    // 查看供应商
    handleView(row) {
      this.$router.push(`/supplier/detail/${row.supplierId}`);
    },

    // 删除供应商
    handleDelete(supplierId) {
      deleteSupplier(supplierId).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.getList();
        } else {
          this.$message.error('删除失败');
        }
      });
    },

    // 评价供应商
    handleEvaluate(row) {
      this.currentSupplierId = row.supplierId;
      this.evaluateDialogVisible = true;
      // 重置表单
      this.$nextTick(() => {
        if (this.$refs.evaluationForm) {
          this.$refs.evaluationForm.resetForm();
        }
      });
    },

    // 提交评价
    submitEvaluation() {
      this.$refs.evaluationForm.validate().then(formData => {
        addEvaluation(formData).then(res => {
          if (res.code === 200) {
            this.$message.success('评价提交成功');
            this.evaluateDialogVisible = false;
            this.getList();
          } else {
            this.$message.error(res.msg || '评价提交失败');
          }
        });
      }).catch(err => {
        console.error('表单验证失败', err);
      });
    },

    // 保存供应商
    saveSupplier() {
      this.$refs.supplierForm.validate(valid => {
        if (valid) {
          if (this.dialogType === 'add') {
            // 新增
            addSupplier(this.form).then(res => {
              if (res.code === 200) {
                this.$message.success('添加成功');
                this.dialogVisible = false;
                this.getList();
              } else if (res.data) {
                // 取出校验失败的信息, 赋给serverValidErrors
                this.serverValidErrors = res.data;
              } else {
                this.$message.error(res.msg || '添加失败');
              }
            });
          } else {
            // 编辑
            updateSupplier(this.form).then(res => {
              if (res.code === 200) {
                this.$message.success('修改成功');
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.msg || '修改失败');
              }
            });
          }
        }
      });
    },

    // 导入供应商
    importSuppliers() {
      this.importDialogVisible = true;
    },

    // 导入成功回调
    handleImportSuccess(response) {
      if (response.code === 200) {
        this.$message.success(`成功导入${response.extend.successCount}条记录`);
        this.importDialogVisible = false;
        this.getList();
      } else {
        this.$message.error(response.msg || '导入失败');
      }
    },

    // 导入失败回调
    handleImportError() {
      this.$message.error('文件上传失败');
    },

    // 导出供应商
    exportSuppliers() {
      // 导出功能实现 - 这里需要后端提供导出接口
      this.$message.info('导出功能开发中');
    },

    // 分页切换
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.searchForm.pageNum = val;
      this.getList();
    },

    // 处理行点击
    handleRowClick(row) {
      this.$refs.supplierTable.toggleRowSelection(row);
    },
  }
}
</script>

<style scoped>
.dialog-footer {
  padding: 10px 0;
  text-align: right;
}
</style>
